<!--
 * @Author: lwHao
 * @Date: 2020-09-20 16:22:26
 * @LastEditors: lwHao
 * @LastEditTime: 2020-09-20 17:05:43
-->
<template>
  <div class="row">
    <p v-if="!user">
      <nuxt-link to="/login">Sign in</nuxt-link>or
      <nuxt-link to="/register">sign up</nuxt-link>to add comments on this article.
    </p>
    <div class="col-xs-12 col-md-8 offset-md-2" v-else>
      <form class="card comment-form" @submit.prevent="onAddComment(body)">
        <div class="card-block">
          <textarea class="form-control" placeholder="Write a comment..." rows="3" v-model.trim="body"></textarea>
        </div>
        <div class="card-footer">
          <img :src="user.image" />
          <button class="btn btn-sm btn-primary" :disabled="!body || submitting">Post Comment</button>
        </div>
      </form>

      <div class="card" v-for="(comment, index) in comments" :key="comment.id">
        <div class="card-block">
          <p class="card-text">{{comment.body}}</p>
        </div>
        <div class="card-footer">
          <nuxt-link :to="{name: 'profile',params: {
            username: comment.author.username
          }}" class="comment-author">
            <img :src="comment.author.image" class="comment-author-img"/>
          </nuxt-link>&nbsp;
          <nuxt-link :to="{name: 'profile',params: {
            username: comment.author.username
          }}" class="comment-author">{{comment.author.username}}</nuxt-link>
          <span class="date-posted">{{comment.createdAt | date('MMM dd,YYYY')}}</span>
          <span class="mod-options" v-if="user.username === comment.author.username" @click="onDeleteComment(comment,index)">
            <!-- <i class="ion-edit"></i> -->
            <i class="ion-trash-a"></i>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getComments, addComment, deleteComments } from '@/api/comments'
import { mapState } from 'vuex'
export default {
  name: 'ArticleComments',
  props: {
    article: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      comments: [],
      body: '',
      submitting: false,
    }
  },
  computed: {
    ...mapState(['user']),
  },
  async mounted() {
    const { data } = await getComments(this.article.slug)
    this.comments = data.comments
  },
  methods: {
    async onAddComment(body) {
      this.submitting = true
      try {
        const { data } = await addComment(this.article.slug, { body })
        this.comments.unshift(data.comment)
        this.body = ''
      } finally {
        this.submitting = false
      }
    },
    async onDeleteComment(comment, index) {
      await deleteComments(this.article.slug, comment.id)
      this.comments.splice(index, 1)
    }
  }
}
</script>

<style>
</style>